<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Benefit extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    /**
     * 初始化授权
     */
    public function initOauth() {
        $openid = $this->session->userdata('openid');
        if (!$openid) {
            $this->ci_wechat->redirectOAuth();
        }
    }

    /**
     * 接收code,授权完成后跳转至首页
     */
    public function checkCode() {
        $info = $this->ci_wechat->initOAuth();
        $this->load->model('FollowModel');
        $this->FollowModel->autoWechatReg($info);
        redirect('benefit/index');
    }

    /**
     * 获取地理信息
     */
    public function baiduApi() {
        $longitude = $this->input->post('longitude');// 经度
        $latitude = $this->input->post('latitude');// 纬度
//        $longitude = '113.908005';
//        $latitude = '22.577255';
		$url = "http://api.map.baidu.com/geocoder?location=" . $latitude . "," . $longitude . "&output=json&key=sTIaxgy1w7TWAv0z3ToKzcRrGffu0gIX&pois=0&coordtype=gcj02ll";
        $str = file_get_contents($url);
        $ret = json_decode($str,true);
        $this->session->set_userdata('city',$ret['result']['addressComponent']['city']);
        echoJson($str);
    }

    public function debug() {
        $longitude = '113.908005';
        $latitude = '22.577255';
        $url = "http://api.map.baidu.com/geocoder?location=" . $latitude . "," . $longitude . "&output=json&key=28bcdd84fae25699606ffad27f8da77b&pois=0&coordtype=gcj02ll";
                $str = file_get_contents($url);
        $ret = json_decode($str,true);
        var_dump($str);
		var_dump($ret);
    }


    /**
     * wechat 首页
     */
    public function index() {
        //        $this->initOauth();

		// 查询session中是否已存在city
		$data['city'] = $this->session->userdata('city');	
        // JS-SDK signPackage
        $data['signdata'] = $this->JsSdk();
        // banner数据
        $this->load->model('BannerModel');
        $data['banner'] = $this->BannerModel->getBannerList(TRUE);
        // 优惠券列表
        $data['coupon'] = $this->getCouponList();
        $this->load->view('wechat/index', $data);
    }

    /**
     * TODO
     * 综合查询筛选,
     * 分页||城市||门店
     * 返回优惠券列表
     */
    private function getCouponList() {
        $this->load->model('CouponModel');
        return $this->CouponModel->getCouponList();
    }

    /**
     * 优惠券详情
     * @param type $id
     */
    public function coupon($id) {
        if (!$id)
            return;
        $this->load->model('CouponModel');
        $data = $this->CouponModel->getCouponDetailById($id);
        var_dump($data);
    }

    public function JsSdk() {
        $signdata = $this->ci_wechat->getJsSign(getCurUrl());
        return $signdata;
    }

    public function test() {
        echo 'Hello ~';
    }

}
